<template>
    <div>
        <el-card class="!border-none" shadow="never">
            <el-page-header :content="$route.query.type == 'pass'?'服务商产品审核':$route.meta.title" @back="$router.back()" />
        </el-card>
        <el-form ref="formRef" :model="formData" :rules="rules">
            <el-card class="!border-none mt-4" shadow="never">
                <el-form-item label="产品名称" prop="name">
                    <div class="w-80">
                        <el-input v-model="formData.name" placeholder="请输入产品名称" type="text" maxlength="30" show-word-limit clearable />
                    </div>
                </el-form-item>
                <el-form-item label="产品类型" prop="type_id">
                    <div class="w-80">
                        <el-radio-group v-model="formData.type_id">
                            <el-radio v-for="(item, index) in cateList" :key="index" :label="item.id">{{ item.name }}</el-radio>
                        </el-radio-group>
                    </div>
                </el-form-item>
                <el-form-item label="服务费比例(%)" prop="fenyong_point">
                    <div class="w-80">
                        <el-input-number v-model="formData.fenyong_point" :min="0" :max="100" />
                    </div>
                </el-form-item>
                <el-form-item label="曝光数" prop="show_num">
                    <div class="w-80">
                        <el-input-number v-model="formData.show_num" :min="0" />
                    </div>
                </el-form-item>
                <el-form-item label="封面图" prop="pics">
                    <div class="w-80">
                        <div>
                            <material-picker v-model="formData.pics" :limit="1" />
                        </div>
                        <div class="form-tips">建议尺寸：200*200px</div>
                    </div>
                </el-form-item>
                <el-form-item label="商品图" prop="info_img_list">
                    <div class="w-80">
                        <div>
                            <material-picker v-model="formData.info_img_list" :limit="6" />
                        </div>
                        <div class="form-tips">建议尺寸：200*200px</div>
                    </div>
                </el-form-item>
                <el-form-item label="展示补贴标签" prop="has_subsidy">
                    <div class="w-80">
                        <el-radio-group v-model="formData.has_subsidy">
                            <el-radio :label="1">是</el-radio>
                            <el-radio :label="0">否</el-radio>
                        </el-radio-group>
                    </div>
                </el-form-item>
                <el-form-item label="产品卖点" prop="label1">
                    <div>
                        <div class="form-tips">最多可填写3个，每个标签最多5个字</div>
                        <div>
                            <div class="w-80 mb-2.5">
                                <el-input v-model="formData.label1" placeholder="请输入" type="text" maxlength="5" show-word-limit clearable />
                            </div>
                            <div class="w-80 mb-2.5">
                                <el-input v-model="formData.label2" placeholder="请输入" type="text" maxlength="5" show-word-limit clearable />
                            </div>
                            <div class="w-80 mb-2.5">
                                <el-input v-model="formData.label3" placeholder="请输入" type="text" maxlength="5" show-word-limit clearable />
                            </div>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="产品规格">
                    <div>
                        <div v-if="!good_id" class="form-tips tips">创建完商品才可以添加规格</div>
                        <div>
                            <div v-if="good_id" class="form-tips tips mb-2">可根据实际业务情况，最少填写一个，可多填</div>
                            <el-table size="large" :data="sku_list" class="mb-4">
                                <el-table-column label="规格/单位" prop="name" min-width="160" />
                                <el-table-column label="售卖金额（元）" prop="price" min-width="160" />
                                <el-table-column label="是否参与补贴" prop="has_subsidy" min-width="160">
                                    <template #default="{ row }">
                                        <span v-if="row.has_subsidy == 1">是</span>
                                        <span v-if="row.has_subsidy == 0">否</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="补贴方式" prop="subsidy_type" min-width="160" >
                                    <template #default="{ row }">
                                        <span v-if="row.subsidy_type == 1">金额</span>
                                        <span v-else-if="row.subsidy_type == 2">返点</span>
                                        <span v-else>-</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="补贴金额" min-width="160" >
                                    <template #default="{ row }">
                                        <span v-if="row.subsidy_type == 1">{{ row.subsidy_money }}</span>
                                        <span v-else-if="row.subsidy_type == 2">{{ row.subsidy_num }}%</span>
                                        <span v-else>-</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" min-width="160" >
                                    <template #default="{ row }" v-if="formData.status != 1">
                                        <el-button v-perms="['server.server/saveGoodSku']" type="primary" link @click="onAdd(row)">编辑</el-button>
                                        <el-button v-perms="['server.server/delGoodSku']" type="danger" link @click="handleSkuDelete(row.id)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                        <div class="flex justify-center" v-if="formData.status != 1">
                            <el-button type="primary" @click="onAdd()" :disabled="!good_id">添加规格</el-button>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item v-if="formData.app_add == 1" label="产品详情">
                    <div class="w-[500px]">
                        <material-picker v-model="formData.app_info_img" :limit="100" />
                    </div>
                    
                </el-form-item>
                <el-form-item v-else label="产品详情">
                    <editor v-if="formData.app_add != 1" v-model="formData.infos" :height="567" />
                </el-form-item>
                <el-form-item label="视频封面">
                    <div class="w-80">
                        <div>
                            <material-picker v-model="formData.video_pics" :limit="1" />
                        </div>
                        <!-- <div class="form-tips">建议尺寸：200*200px</div> -->
                    </div>
                </el-form-item>
                <el-form-item label="视频链接">
                    <div>
                        <material-picker v-model="formData.video_link" type="video" :limit="1"/>
                    </div>
                </el-form-item>
            </el-card>
        </el-form>

        <product-add ref="productSku" v-model:show="checkState.show"  @confirm="handleConfirmCheck" />
        
        <footer-btns v-if="formData.status != 3">
            <el-button @click="handleSave" type="primary" v-prevent-reclick="3000">保存</el-button>
            <el-button  @click="()=>{$router.back()}">取消</el-button>
        </footer-btns>

        <footer-btns v-if="formData.status == 3">
            <el-button @click="handleSave" type="primary" v-prevent-reclick="3000">保存</el-button>
            <el-button @click="handlePass" type="primary" v-prevent-reclick="3000">审核通过</el-button>
            <el-button type="danger"  @click="handleReject">审核驳回</el-button>
        </footer-btns>
        <check_demand v-model:show="checkStateReject.show" :value="checkStateReject.value" @confirm="handleConfirmCheckReject"></check_demand>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus';
import { userCate, saveGood, goodInfo, saveGoodSku, delGoodSku, changeGoodStatus } from '@/api/service';
import productAdd from './productAdd.vue'
import useMultipleTabs from '@/hooks/useMultipleTabs'
import feedback from '@/utils/feedback';
 import check_demand from './check_demand.vue'

const route = useRoute()
const router = useRouter()
const good_id:any = ref('')

if (route.query.id) {
    good_id.value = route.query.id
}

const productSku = ref()
const checkState = reactive({
    show: false,
    value: '',
    status: ''
})

const handleConfirmCheck = async (value : any) => {
    console.log(value)
    checkState.show = false
    await saveGoodSku({...value,good_id: good_id.value})
    feedback.msgSuccess('规格保存成功')
    getDetail()
}
// 新增sku和编辑sku
const onAdd = (row?:any) => {
    checkState.show = true;
    console.log(row)
    if (productSku.value) {
        productSku.value.edit_data(row)
    }
}
// 删除sku
const handleSkuDelete = async (id:number) => {
    console.log(id)
    await feedback.confirm('是否确认完成此操作', '商品规格删除')
    await delGoodSku({id})
    getDetail()
}

const cateList:any = ref([])
const getCateList = async () => {
    const res = await userCate({server_id: route.query.server_id})
    console.log(res)
    cateList.value = res.list;
    if (!good_id.value) {
        formData.type_id = res.list[0].id;
    }
   
    console.log(cateList.value)
}
getCateList()

const formData:any = reactive({
    id: '',
    name: '',
    server_id: '',
    fenyong_point: 0,
    show_num: 0,
    type_id: '',
    pics: '',
    info_img_list: [],
    label1: '',
    label2: '',
    label3: '',
    tags: [],
    infos:'',
    has_subsidy: 0,
    status: 0,
    app_add: 0,
    app_info_img: [],
    video_pics: '',
    video_link: ''
})
const rules = reactive({
    name: [{ required: true, message: '请填写产品名称', trigger: 'blur' }],
    type_id: [{ required: true, message: '请选择产品类型', trigger: 'blur' }],
    pics: [{ required: true, message: '请上传封面图', trigger: 'blur' }],
    info_img_list: [{ required: true, message: '请上传商品图', trigger: 'blur' }],
    has_subsidy: [{ required: true, message: '请选择展示补贴标签', trigger: 'blur' }],
    label1: [{ required: true, message: '请填写产品卖点', trigger: 'blur' }]
})

const {removeTab} = useMultipleTabs()
const formRef = shallowRef<FormInstance>()

const handleSave = async () => {
    await formRef.value?.validate()
    formData.tags = [];
    if ( formData.label1.length > 0) {
        formData.tags.push(formData.label1)
    }
    if ( formData.label2.length > 0 ) {
        formData.tags.push(formData.label2)
    }
    if ( formData.label3.length > 0 ) {
        formData.tags.push(formData.label3)
    }
    console.log(formData)
    formData.server_id = route.query.server_id;
    if (formData.infos == "<p><br></p>") {
        formData.infos = ''
    }
    // 新建或者更新商品
    const res = await saveGood(formData)
    console.log(res)
    formData.id = res.id;
    if (good_id.value) {
        feedback.msgSuccess('保存成功')
        removeTab()
        router.back()
    } else{
        feedback.msgSuccess('新建成功')
        good_id.value = res.id;
    }
}

const sku_list:any = ref([])
const getDetail = async () => {
    const res = await goodInfo({
        good_id: good_id.value
    })
    console.log(res)
    Object.keys(formData).forEach((key) => {
        //@ts-ignore
        formData[key] = res.info[key]
    })
    formData.label1 = formData.tags[0] || '';
    formData.label2 = formData.tags[1] || '';
    formData.label3 = formData.tags[2] || '';

    sku_list.value = res.sku_list;
}
good_id.value && getDetail();

//审核通过
const handlePass = async () => {
    await changeGoodStatus({
        id: formData.id,
        status: 1,
        notice: ''
    })
    removeTab()
    router.back()
}
const checkStateReject = reactive({
    show: false,
    value: '',
    status: ''
})
const handleReject = () => {
    checkStateReject.show = true
    checkStateReject.value = formData.id
}
const handleConfirmCheckReject = async (value : any) => {
    console.log(value)
    await changeGoodStatus({
        id: value.id,
        status: 4,
        notice: value.reason
    })
    checkStateReject.show = false;
    removeTab()
    router.back()
}

</script>
<style scoped lang="scss">
.tips{
    color: var(--el-color-primary) !important;
}
</style>